from flask import Flask, request, jsonify
from flask_httpauth import HTTPBasicAuth
from flask_cors import CORS
from datetime import datetime, timedelta
import csv
import secrets
import redis
import psutil
import os
import ssl

app = Flask(__name__)
auth = HTTPBasicAuth()
CORS(app)
r = redis.Redis()

# 载入用户名和密码到字典中（从/etc/ansible/users.csv文件）
users = {}
with open('/etc/ansible/users.csv', 'r') as csvfile:
    csv_reader = csv.reader(csvfile)  # 使用csv.reader读取csvfile中的文件
    header = next(csv_reader)  # 读取第一行每一列的标题
    for row in csv_reader:  # 将csv 文件中的数据保存到data中
        for index in row:
            info = index.split(";")
            users[info[1]] = info[2]


# 配置SSL证书和密钥
# context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
# context.load_cert_chain(certfile='/path/to/cert.pem', keyfile='/path/to/key.pem')

# 认证函数
@auth.verify_password
def verify_password(username, password):
    if username in users and password == users[username]:
        return username


# 路由: 获取系统统计数据
@app.route('/stats', methods=['GET'])
@auth.login_required
def get_stats():
    ram_free = psutil.virtual_memory().available // 1024 // 1024
    uptime = str(datetime.now() - datetime.fromtimestamp(psutil.boot_time()))
    api_pid = os.getpid()
    api_prio = os.nice(0)
    total_proc = psutil.cpu_count()
    return jsonify({
        'ram_free': ram_free,
        'uptime': uptime,
        'api_pid': api_pid,
        'api_prio': api_prio,
        'total_proc': total_proc
    })


# 路由: 登录并获取访问令牌
@app.route('/login', methods=['POST'])
@auth.login_required
def login():
    token = secrets.token_hex(16)
    r.set(token, auth.current_user())
    r.expire(token, timedelta(seconds=90))
    return jsonify({'token': token})


# 路由:注销用户
@app.route('/logout', methods=['POST'])
@auth.login_required
def logout():
    token = request.headers.get('token')
    r.delete(token)
    return jsonify({'message': 'Logged out'})


# 路由: 获取当前用户
@app.route('/whoami', methods=['GET'])
@auth.login_required
def whoami():
    return jsonify({'username': auth.current_user()})


if __name__ == '__main__':
    # app.run(host='10.22.0.50', port=443, ssl_context=context, threaded=True)
    app.run(host='10.22.0.50', port=443, threaded=True)

